<template>
  <Dialog v-model="visible" width="700px">
    <template #title> <div class="text-18px color-#172b4d"> 场景管理 </div> </template>
    <Flexbox class="scene-list">
      <div class="scene-list-box">
        <Flexbox class="scene-list-head">
          <el-checkbox
            :indeterminate="isleftIndeterminate"
            v-model="checkleftAll"
            @change="handleleftCheckAllChange"
          />
          <div class="scene-list-head-name !color-#172b4d">显示的标签</div>
          <div class="scene-list-head-detail !color-#172b4d">{{
            leftCheckNum + '/' + leftAllNum
          }}</div>
        </Flexbox>
        <div class="scene-list-body">
          <draggable
            :sort="false"
            v-model="addAndEditSceneList"
            item-key="index"
            :animation="200"
            filter=".component-toolbar"
            ghost-class="draggable-ghost"
            :force-fallback="true"
            group="component"
            @change="leftMoveEnd"
          >
            <template #item="{ element }">
              <Flexbox class="list-item" v-if="element.status == 1">
                <div class="flex item-center pl-9px">
                  <el-checkbox v-model="element.check" class="list-item-check" />
                  <div
                    style="display: flex; align-items: center"
                    class="ml-10px text-12px !color-#172b4d"
                    >{{ element.name }}</div
                  >
                </div>
                <div class="flex item-center">
                  <Icon
                    class="hover-color mr-10px"
                    icon="ep:edit"
                    @click="itemHandle('edit', element)"
                  />
                  <Icon
                    class="hover-color"
                    icon="ep:delete"
                    @click="itemHandle('delete', element)"
                  />
                </div>
              </Flexbox>
            </template>
          </draggable>
        </div>
      </div>
      <div class="scene-middle-list">
        <el-button
          :class="{ 'scene-middle-button-select': isToLeft }"
          :disabled="!isToLeft"
          class="scene-middle-left-button"
          @click="changePositon('left')"
        >
          <el-icon :color="isToLeft ? '#fff' : ''"><ArrowLeft /></el-icon>
        </el-button>
        <el-button
          :class="{ 'scene-middle-button-select': isToRight }"
          :disabled="!isToRight"
          class="scene-middle-right-button"
          @click="changePositon('right')"
        >
          <el-icon :color="isToRight ? '#fff' : ''"><ArrowRight /></el-icon>
        </el-button>
      </div>
      <div class="scene-list-box">
        <Flexbox class="scene-list-head">
          <el-checkbox
            :indeterminate="isrightIndeterminate"
            v-model="checkrightAll"
            @change="handlerightCheckAllChange"
          />
          <div class="scene-list-head-name !color-#172b4d">隐藏的标签</div>
          <div class="scene-list-head-detail !color-#172b4d">{{
            rightCheckNum + '/' + rightAllNum
          }}</div>
        </Flexbox>
        <div class="scene-list-body">
          <draggable
            v-model="addAndEditSceneList"
            :sort="false"
            item-key="index"
            :animation="200"
            filter=".component-toolbar"
            ghost-class="draggable-ghost"
            :force-fallback="true"
            group="component"
            @change="rightMoveEnd"
          >
            <template #item="{ element }">
              <Flexbox class="list-item" v-if="element.status == 0">
                <div class="flex item-center pl-9px">
                  <el-checkbox v-model="element.check" class="list-item-check" />
                  <div
                    style="display: flex; align-items: center"
                    class="ml-10px text-12px !color-#172b4d"
                    >{{ element.name }}</div
                  >
                </div>
              </Flexbox>
            </template>
          </draggable>
        </div>
      </div>
    </Flexbox>
    <div class="handle-bar">
      <div class="handle-bar-add !color-#42526e" @click="addAndEditScene">+ 新建场景</div>
    </div>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button @click="handleConfirm" type="primary">保存</el-button>
    </template>
  </Dialog>
  <SceneCreate ref="sceneCreateRef" @success="getList" />
</template>

<script setup>
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import * as AdvancedQueryApi from '@/api/crm/advancedQuery/index.ts'
import SceneCreate from './SceneCreate.vue'
import draggable from 'vuedraggable'
const message = useMessage()

/**crm类型*/
const crmType = ref(null)
/**默认场景id*/
const default_id = ref('')
/**控制展示*/
const visible = ref(false)
/**标注头部是多选框效果*/
const isleftIndeterminate = ref(false)
/**关联全选操作多选框*/
const checkleftAll = ref(false)
const isrightIndeterminate = ref(false)
const checkrightAll = ref(false)

/**显示场景管理*/
const open = (type) => {
  visible.value = true
  crmType.value = type
  getSceneList()
}
const emit = defineEmits(['success'])
/**刷新数据*/
const getList = () => {
  getSceneList()
  emit('success')
}
defineExpose({ open })

const addAndEditSceneList = ref([])
/**获取列表*/
const getSceneList = async () => {
  const data = await AdvancedQueryApi.querySceneList({ page: crmType.value })
  data.forEach((item) => {
    item.check = false
  })
  addAndEditSceneList.value = data
}

/**确定选择*/
const handleConfirm = async () => {
  try {
    for (const key in addAndEditSceneList.value) {
      addAndEditSceneList.value[key].params = JSON.parse(addAndEditSceneList.value[key].params)
      await AdvancedQueryApi.querySceneUpdate(addAndEditSceneList.value[key])
    }
    ElMessage.success('保存成功!')
    emit('success')
    visible.value = false
  } catch {}
}

const sceneCreateRef = ref(null)
/**事项操作*/
const itemHandle = async (type, item) => {
  //删除
  if (type == 'delete') {
    await message.delConfirm()
    await AdvancedQueryApi.querySceneDelete(item.id)
    ElMessage.success('操作成功!')
    await getSceneList()
    if (addAndEditSceneList.value.length == 0) {
      emit('success')
    }
  } else {
    // 编辑
    sceneCreateRef.value.open('edit', crmType.value, item)
  }
}
/**添加and编辑场景*/
const addAndEditScene = () => {
  sceneCreateRef.value.open('create', crmType.value)
}
/**默认操作*/
const defaultHandle = () => {}

/**取消选择*/
const handleCancel = () => {
  visible.value = false
}
/**拖拽结束事件*/
const leftMoveEnd = (evt) => {}
const rightMoveEnd = (evt) => {}
/**选择全部*/
const handleleftCheckAllChange = (value) => {
  addAndEditSceneList.value.forEach((item) => {
    if (item.status == 1) {
      item.check = value
    }
  })
}
/**选择全部*/
const handlerightCheckAllChange = (value) => {
  addAndEditSceneList.value.forEach((item) => {
    if (item.status == 0) {
      item.check = value
    }
  })
}

/**左侧是否全选*/
watch(
  () => addAndEditSceneList.value,
  (val) => {
    if (val) {
      const data = val.filter((item) => item.status == 1)
      if (data.length) {
        checkleftAll.value = data.every((item) => item.check)
      } else {
        checkleftAll.value = false
      }

      const data2 = val.filter((item) => item.status == 0)
      if (data2.length) {
        checkrightAll.value = data2.every((item) => item.check)
      } else {
        checkrightAll.value = false
      }
    }
  },
  { immediate: true, deep: true }
)
/**左侧是否有值*/
const isToRight = computed(() => {
  return addAndEditSceneList.value.some((item) => item.check && item.status == 1)
})
/**右侧是否有值*/
const isToLeft = computed(() => {
  return addAndEditSceneList.value.some((item) => item.check && item.status == 0)
})
/**左侧未选*/
const leftCheckNum = computed(() => {
  return addAndEditSceneList.value.filter((item) => item.status == 1 && item.check).length
})
/**左侧总数*/
const leftAllNum = computed(() => {
  return addAndEditSceneList.value.filter((item) => item.status == 1).length
})
/**右侧未选*/
const rightCheckNum = computed(() => {
  return addAndEditSceneList.value.filter((item) => item.status == 0 && item.check).length
})
/**右侧总数*/
const rightAllNum = computed(() => {
  return addAndEditSceneList.value.filter((item) => item.status == 0).length
})
/**按钮操作*/
const changePositon = (type) => {
  // 从右往左
  if (type == 'left') {
    addAndEditSceneList.value.forEach((item) => {
      if (item.check) {
        item.check = false
        item.status = 1
      }
    })
  } else {
    addAndEditSceneList.value.forEach((item) => {
      if (item.check) {
        item.check = false
        item.status = 0
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.scene-name {
  font-size: 12px;
  padding-bottom: 5px;
  color: #aaa;
}

.default-mark {
  width: 4px;
  height: 4px;
  border-radius: 2px;
  margin-right: 5px;
}
.default-mark-active {
  background-color: #4b74ff;
}

.scene-list {
  user-select: none;

  .scene-list-box {
    flex: 1;
    border: 1px solid #e6e6e6;
    border-radius: 2px;
    height: 300px;
    position: relative;
    padding: 15px;
  }
  .scene-middle-list {
    width: 50px;
    text-align: center;
    button {
      border: 1px solid #cccccc;
      width: 34px;
      height: 34px;
      border-radius: 17px;
      background-color: #f5f7fa;
    }
    .scene-middle-icon {
      color: #cccccc;
      font-size: 14px;
    }
    .scene-middle-right-button {
      margin-top: 15px;
      margin-left: 0;
    }

    .scene-middle-button-select {
      border: 1px solid #4b74ff !important;
      background-color: #4b74ff !important;
      .scene-middle-icon {
        color: white !important;
      }
    }
  }
  .scene-list-head {
    padding-bottom: 15px;
    padding-left: 9px;
    border-bottom: 1px dashed #e6e6e6;
    font-size: 13px;
    .scene-list-head-name {
      color: #333;
      flex: 1;
      margin: 0 8px;
    }

    .scene-list-head-detail {
      color: #aaa;
    }
  }
  .scene-list-body {
    padding: 5px 0;
    height: 240px;
    position: relative;
    overflow-y: auto;
  }

  .list-item {
    padding: 5px 0;
    background-color: white;
    justify-content: space-between;
    align-items: center;
    height: 26px;
    cursor: pointer;
    .list-item-check {
      margin-right: 8px;
    }
    .list-item-name {
      font-size: 13px;
      color: #333;
      flex: 1;
    }
  }
}
.hover-color:hover {
  color: #4b74ff;
}

.handle-bar {
  font-size: 12px;
  .handle-bar-add {
    cursor: pointer;
    color: #2362fb;
    padding: 20px 10px 0;
  }
  .handle-bar-save {
    position: relative;
    height: 30px;
    button {
      float: right;
      margin-right: 10px;
    }
  }
}
</style>
